package cn.bsuc.crm.controller;

import cn.bsuc.crm.entity.Role;
import cn.bsuc.crm.service.RoleService;
import cn.bsuc.crm.util.Code;
import cn.bsuc.crm.util.Result;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@RestController
@RequestMapping("/role")
@CrossOrigin
public class RoleController {

    @Autowired
    private RoleService roleService;

    //保存角色
    @PostMapping("/saveRole")
    public Result save(@RequestBody Role role){
        int i = roleService.saveRole(role);
        if (i == 1){
            return Result.ok();
        }else if (i == 0){
            return  Result.fail(Code.ERROR,"保存失败");
        }else {
            return Result.fail(Code.SYSTEM_ERR,"系统出错");
        }
    }
    //查询所有角色
    @GetMapping("/selectAllRole")
    public Result selectRole(Integer id){
        if (id!=null){
            Role byId = roleService.getById(id);
            if (byId != null){
                return Result.ok(byId);
            }else if (byId == null){
                return  Result.fail(Code.ERROR,"查询不到角色");
            }else {
                return Result.fail(Code.SYSTEM_ERR,"系统出错");
            }
        }else {
            List<Role> list = roleService.list();
            if (list.size() != 0){
                return Result.ok(list);
            }else if (list.size() == 0){
                return  Result.fail(Code.ERROR,"查询不到角色");
            }else {
                return Result.fail(Code.SYSTEM_ERR,"系统出错");
            }
        }
    }

    //查询所有角色及分页
    @GetMapping("/selectAllRolex")
    public Result selectAllRolex(@RequestParam(defaultValue = "1") Integer pageNo,
                                @RequestParam(defaultValue = "3")Integer pageSize){
        Page<Role> rolePage = roleService.selectAllrole(pageNo,pageSize);
        return Result.ok(rolePage);

    }

    //删除角色及权限
    @GetMapping("/deleteRoleAndPermission")
    public Result deleteRoleAndPermission( Integer roleId){
        int i = roleService.deleteRoleAndPermission(roleId);
        if (i == 1){
            return Result.ok();
        }else if (i == 0){
            return  Result.fail(Code.ERROR,"删除失败");
        }else {
            return Result.fail(Code.SYSTEM_ERR,"系统出错");
        }
    }
}

